package com.yulang.web.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yulang.security.BaseResult;
import com.yulang.web.pojo.SysRole;
import com.yulang.web.service.SysRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/role")
public class SystemRoleController {

    private static final String HTML_PREFIX = "system/role/";

    @Autowired
    private SysRoleService sysRoleService;

    @PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping(value = {"/",""})
    public String role(){
        return HTML_PREFIX + "role-list";
    }


    @PreAuthorize("hasAuthority('sys:role:list')")
    @PostMapping("/page")
    @ResponseBody
    public BaseResult page(Page page, SysRole sysRole){
        QueryWrapper<SysRole> query = new QueryWrapper<>();
        query.lambda().like(StringUtils.isNotEmpty(sysRole.getName()), SysRole::getName,sysRole.getName());
        return BaseResult.ok(sysRoleService.page(page,query));
    }

    @PreAuthorize("hasAnyAuthority('sys:role:add','sys:role:edit')")
    @GetMapping({"/form","/form/{id}"})
    public String form(@PathVariable(required = false) String id, Model model){
        SysRole sysRole;
        if(id==null){
            sysRole = new SysRole();
        }else{
            sysRole = sysRoleService.findById(id);
        }
        model.addAttribute("role",sysRole);
        return HTML_PREFIX + "/role-form";
    }

    @PreAuthorize("hasAnyAuthority('sys:role:add','sys:role:edit')")
    @PutMapping
    public String saveOrUpdate(SysRole sysRole){
        sysRoleService.saveOrUpdateRolePermission(sysRole);
        return "redirect:/role";
    }

    @ResponseBody
    @PreAuthorize("hasAuthority('sys:role:delete')")
    @DeleteMapping("/{id}")
    public BaseResult delete(@PathVariable Long id){
        sysRoleService.delete(id);
        return BaseResult.ok(true);
    }


}
